package com.example.demo.offer;


public class Offer21 {
    public static void main(String[] args) {
        ListNode l5 = new ListNode(5);
        ListNode l4 = new ListNode(4,l5);
        ListNode l3 = new ListNode(3,l4);
        ListNode l2 = new ListNode(2,l3);
        ListNode head = new ListNode(1,l2);
        ListNode listNode = removeNthFromEnd(head, 2);
        while (listNode != null){
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode tmp = new ListNode(0,head);
        int lenth = getLenth(head);
        ListNode cur = tmp;
        for (int i = 1; i < lenth - n +1; i++) {
            cur =  cur.next;
        }
        cur.next = cur.next.next;
        return tmp.next;
    }

    private static int getLenth(ListNode head) {
        if(head == null){
            return 0;
        }
        int lenth = 0;
        while (head != null){
            head = head.next;
            lenth++;
        }
        return lenth;
    }


}

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
